package org.spring.blog.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil {

    /**
     * cookie 的默认保存时间
     */
    public static final int default_age = LRConstants.TimeValue.day_s;

//    public static String domain = "localhost";

    public static void setUpCookie(HttpServletResponse _response, String _key, String _value) {
        setUpCookie(_response, _key, _value, default_age);
    }


    /**
     * 创建一个cookie
     *
     * @param _response 响应体
     * @param _key      键
     * @param _value    值
     * @param age       生命周期
     */
    public static void setUpCookie(HttpServletResponse _response, String _key, String _value, int age) {
        Cookie cookie = new Cookie(_key, _value);

        cookie.setPath("/");
        // TODO: 布置到自己的服务器上的时候 改成自己的域名
        // 没买域名就不设置 默认设置成布置的服务器ip
//        cookie.setDomain(domain);
        cookie.setMaxAge(age);
        _response.addCookie(cookie);
    }

    /**
     * 获取一个cookie 值
     *
     * @param _request 请求体
     * @param _key     键
     * @return cookie 值
     */
    public static String getCookieValue(HttpServletRequest _request, String _key) {

        Cookie[] cookies = _request.getCookies();

        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (_key.equals(cookie.getName())) {
                    return cookie.getValue();
                }
            }
        }

        return null;
    }

    /**
     * 删除cookie
     *
     * @param _response 响应体
     * @param _key      键
     */
    public static void deleteCookie(HttpServletResponse _response, String _key) {
        setUpCookie(_response, _key, null, 0);
    }
}
